package com.example.wotu;

import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link FragWLOpenBook.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link FragWLOpenBook#newInstance} factory method to
 * create an instance of this fragment.
 */
public class FragWLOpenBook extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;
    private View view;
    private String url = null,A = null,wurl = null;
    private String[] B = null;
    private int num = 0,booksize = 0;
    private TextView booA;
    private TextView booB;
    private TextView booC;
    private TextView booD;
    private TextView booE;
    private ListView bookLB;
    private Handler handler;
    private ArrayList<String> bookSname,bookSurl;
    private ArrayAdapter aapta;
    private ImageView gobacks;
    private ImageView Fand;
    private Fragment fraglook;
    private FrameLayout fraglooklay;
    private LinearLayout openbook;

    public FragWLOpenBook() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment FragWLOpenBook.
     */
    // TODO: Rename and change types and number of parameters
    public static FragWLOpenBook newInstance(String param1, String param2) {
        FragWLOpenBook fragment = new FragWLOpenBook();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        //******* 102 *******
        view = inflater.inflate(R.layout.frag_wlopen_book, container, false);
        mListener.onNOT_WK(102);
        num = getArguments().getInt("num");
        url = getArguments().getString("LV");
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        getFindV();
        getRUNN();

        //1.返回；2.点击；3.存储（保存时存储的是标题与链接，下载后存储的是标题与内容）
        gobacks.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mListener.onGoBack(102);
            }
        });
        bookLB.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if(wurl == null){
                    wurl = bookSurl.get(i);
                    fraglook = new FragWLLookBook();
                }else{
                    if(!wurl.equals(bookSurl.get(i))) fraglook = new FragWLLookBook();
                }
                //关闭二层（父父层）：为下一层消除重叠效果
//                mListener.onGoBack(102);
                openbook.setVisibility(View.GONE);
                fraglooklay.setVisibility(View.VISIBLE);

                Bundle LJ = new Bundle();
                LJ.putInt("num",i);
                LJ.putInt("numZJ",Integer.parseInt(booE.getText().toString()));
                LJ.putStringArrayList("ZJname",bookSname);
                LJ.putStringArrayList("ZJ",bookSurl);
                fraglook.setArguments(LJ);
                getChildFragmentManager().beginTransaction().replace(R.id.LOOKS,fraglook).commitAllowingStateLoss();
            }
        });
        Fand.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //需要数据库
            }
        });
    }

    //1.实例id；2.链接数据
    public void getFindV(){
        booA = view.findViewById(R.id.bookna);
        booB = view.findViewById(R.id.bookzz);
        booC = view.findViewById(R.id.bookzhgx);
        booD = view.findViewById(R.id.bookzxzj);
        booE = view.findViewById(R.id.bookzjml);
        gobacks = view.findViewById(R.id.goback);
        bookLB = view.findViewById(R.id.bookLV);
        Fand = view.findViewById(R.id.fand);
        bookSname = new ArrayList<>();
        bookSurl = new ArrayList<>();
        fraglooklay = view.findViewById(R.id.LOOKS);
        openbook = view.findViewById(R.id.openbook);
    }
    private void getRUNN(){
        if(num == 0){

        }
        else if(num == 1){
            //笔趣阁
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    booksize = 0;
                    Document document = null;
                    try {
                        document = Jsoup.connect(url).get();
                        Element content = document.getElementById("info");
                        Elements a = content.getElementsByTag("h1");
                        Elements b = content.getElementsByTag("p");
                        B = String.valueOf(b.text()).replaceAll("作 者：|动 作：加入书架, 投推荐票, 直达底部 最后更新：|最新章节：","").split(" ");
                        A = a.text();
                        Element contents = document.getElementById("list");
                        Elements c = contents.getElementsByTag("a");
                        for (Element link : c) {
                            //为：链接地址；名字
                            String linkHref = link.attr("href");
                            String linkText = link.text();
                            bookSname.add(linkText);
                            bookSurl.add(linkHref);
                            booksize++;
                        }
                        handler.sendMessage(handler.obtainMessage(0));
                    } catch (IOException exception) {
                        exception.printStackTrace();
                    }
                }
            };
            new Thread(runnable).start();
            handler = new Handler(){
                @Override
                public void handleMessage(@NonNull Message msg) {
                    super.handleMessage(msg);
                    if(msg.what == 0){
                        booA.setText(A);
                        booB.setText(B[0]);
                        booC.setText(B[1]+" "+B[2]);
                        booD.setText(B[3]);
                        booE.setText(String.valueOf(booksize));
                        aapta = new ArrayAdapter(getActivity(),R.layout.support_simple_spinner_dropdown_item,bookSname);
                        bookLB.setAdapter(aapta);
                    }
                }
            };
        }
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
        void onGoBack(int f);
        void onNOT_WK(int wk);
    }
}
